package com.itheima.heimatoutiaosso.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.heimatoutiaosso.domain.po.WmUser;
import com.itheima.heimatoutiaosso.domain.dto.WmUserDto;
import com.itheima.heimatoutiaosso.mapper.WmUserMapper;
import com.itheima.heimatoutiaosso.service.WmUserService;
import com.itheima.heimatoutiaosso.uitl.BCryptPasswordEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmUserServiceImpl extends SuperServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private   String key ="123456";

    @Override
    public String login(WmUserDto dto) {
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName, dto.getName());
        WmUser wmUser = this.getOne(wrapper);
        if (wmUser == null) {
            return null;
        }
        // 验证token
        log.info(bCryptPasswordEncoder.encode(dto.getPassword()));
        if (!bCryptPasswordEncoder.matches(dto.getPassword(), wmUser.getPassword())) {
            //密码不对，不需要签发token
            return null;
        }
        String token = JWT.create().setPayload("id", wmUser.getId()).setKey(key.getBytes()).sign();
        return token;
    }
}
